﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Primitives;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Polaris.WebApi.Swagger
{
    public class AuthorizationHeaderOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            // 检查是否已经存在 Authorization 头
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<OpenApiParameter>();
            }

            var existingAuthParameter = operation.Parameters.FirstOrDefault(p => p.Name == "Authorization");

            // 如果不存在 Authorization 头，则添加
            if (existingAuthParameter == null)
            {
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Description = "JWT token",
                    Required = true,
                    Schema = new OpenApiSchema
                    {
                        Type = "String"
                    },
                    Example = new OpenApiString("Bearer ") // 设置默认的示例值
                });
            }
            else
            {
                // 如果存在 Authorization 头，确保其示例值以 "Bearer " 开头
                existingAuthParameter.Example = new OpenApiString("Bearer ");
            }
        }
    }
}
